#!/usr/bin/env python
# -*- coding:utf-8 -*-


@staticmethod
def make_bean_base_obj(data, attr_ary, val_ary, target_file):
    import os
    _bean_file_path = os.path.dirname(target_file) + "\\" + data["#beanName#"] + ".py"
    with open(_bean_file_path, 'r', encoding='utf-8') as _read_file:
        base_arry = _read_file.read()
    _str_DATA_COLUMN = "    DATA_COLUMN = [" + "\"" + "\", \"".join(attr_ary) + "\"" + "]"
    _str_TABLE_NAME = f"    TABLE_NAME = '{data['#tableName#']}'"
    with open(target_file, 'w', encoding='utf-8') as _tmp_file:
        ## 输出原始对象内容
        [_tmp_file.write(item) for item in base_arry]
        _tmp_file.write("\n\n")
        _tmp_file.write(_str_DATA_COLUMN)
        _tmp_file.write("\n")
        _tmp_file.write(_str_TABLE_NAME)
        _tmp_file.write("\n\n")
        _tmp_file.write("    def __init__(self):\n")
        for idx in range(0, len(attr_ary)):
            # _tmp_file.write(f"        self.{attr_ary[idx]}={'\'\'' if isinstance(val_ary[idx],str) and len(val_ary[idx]) ==0 else val_ary[idx]}\n")
            if isinstance(val_ary[idx], str) and len(val_ary[idx]) == 0:
                val = "''"
            else:
                val = val_ary[idx]
            _tmp_file.write(f"        self.{attr_ary[idx]} = {val} \n")
        _tmp_file.write("\n")
        _tmp_file.write(f"    @staticmethod")
        _tmp_file.write(f"    def my{data['#beanName#']}({', '.join(attr_ary)}):\n")
        for key in attr_ary:
            _tmp_file.write(f"        if isinstance({key}, int):\n")
            _tmp_file.write(f"            _{key} = int({key})\n")
            _tmp_file.write(f"        elif isinstance({key}, list):\n")
            _tmp_file.write(f"            _{key} = json.dumps({key}, ensure_ascii=False)\n")
            _tmp_file.write(f"        else:\n")
            _tmp_file.write(f"            _{key} = str({key})\n")
            _tmp_file.write(f"        self.{key} = _{key}\n\n")
        return


@staticmethod
def make_split_data_clum(clas_name, target_file):
    txt_content = []
    txt_content.append("\n")
    txt_content.append("    @staticmethod")
    txt_content.append("    def split_data_clum(with_id):")
    txt_content.append(f"        converted_columns = [{clas_name}.convert_to_snake_case(column) for column in {clas_name}.DATA_COLUMN]")
    txt_content.append("        ary = []")
    txt_content.append("        if with_id:")
    txt_content.append("            ary.append(\"id\")")
    txt_content.append(f"        [ary.append(item) for item in converted_columns]")
    txt_content.append("        return \"`\"+\"`,`\".join(ary)+\"`\"")
    append_to_file(target_file, "\n".join(txt_content))


@staticmethod
def make_split_params(attr_ary, target_file):
    txt_content = []
    txt_content.append("\n")
    txt_content.append("    @staticmethod")
    txt_content.append("    def split_params(params):")
    txt_content.append("        g_param = []")
    # 循环类中定义的变量
    for key in attr_ary:
        # txt_content.append(f"{key}: {value}")
        ##         if params.psno is not None and len(params.psno) > 0:
        # g_param.append('`psno`=' + "\'" + params.psno + "\'")
        txt_content.append("        if params." + key + " is not None and len(params." + key + ") > 0:")
        txt_content.append(
            "            g_param.append('`" + key + "`='+" + "\"" + "\\'" + "\"" + "+params." + key + "+\"" + "\\'\")")
    txt_content.append("        return ', '.join(str(i) for i in g_param)")
    append_to_file(target_file, "\n".join(txt_content))


@staticmethod
def make_to_string(attr_ary, clas_name, target_file):
    txt_content = []
    txt_content.append("\n")
    txt_content.append("    @staticmethod")
    txt_content.append("    def to_string(with_flg):")
    txt_content.append("        g_param = []")
    txt_content.append("        if with_flg:")
    # 循环类中定义的变量
    for key in attr_ary:
        txt_content.append("            g_param.append(\"`" + clas_name + "`.`" + key + "`\")")
    txt_content.append("        else:")
    for key in attr_ary:
        txt_content.append("            g_param.append(\"`" + key + "`\")")
    txt_content.append("        return ', '.join(str(i) for i in g_param)")
    append_to_file(target_file, "\n".join(txt_content))


@staticmethod
def make_to_string_noId(attr_ary, clas_name, target_file):
    txt_content = []
    txt_content.append("\n")
    txt_content.append("    @staticmethod")
    txt_content.append("    def to_string_noId():")
    txt_content.append("        g_param = []")
    for key in attr_ary:
        txt_content.append("        g_param.append(\"`" + clas_name + "`.`" + key + "`\")")
    txt_content.append("        return ', '.join(str(i) for i in g_param)")
    append_to_file(target_file, "\n".join(txt_content))


@staticmethod
def make_chg_data_2_dict(clas_name, target_file):
    txt_content = []
    txt_content.append("\n")
    txt_content.append("    @staticmethod")
    txt_content.append("    def chg_data_2_dict(with_id, obj):")
    txt_content.append("        convert = dict()")
    txt_content.append("        ary = []")
    txt_content.append("        if with_id:")
    txt_content.append("            ary.append(\"id\")")
    txt_content.append("        [ary.append(item) for item in " + clas_name + ".DATA_COLUMN]")
    txt_content.append("        for clu_index in range(0, len(ary)):")
    txt_content.append("            if ary[clu_index] == \"id\":")
    txt_content.append("                convert[ary[clu_index]] == int(obj[clu_index])")
    txt_content.append("            else:")
    txt_content.append("                convert[ary[clu_index]] == str(obj[clu_index]).replace(\"\t\", \"\")")
    txt_content.append("        return convert")
    append_to_file(target_file, "\n".join(txt_content))


@staticmethod
def make_chg_dict_2_data(attr_ary, target_file):
    txt_content = []
    txt_content.append("\n")
    txt_content.append("    @staticmethod")
    txt_content.append("    def chg_dict_2_data(with_id, obj):")
    txt_content.append("        if with_id:")
    txt_content.append("            data = [")
    for key in attr_ary:
        txt_content.append("                str(obj." + key + "),")
    txt_content.append("            ]")
    txt_content.append("        else:")
    txt_content.append("            data = [")
    for key in attr_ary:
        txt_content.append("               str(obj." + key + "),")
    txt_content.append("        ]")
    txt_content.append("        return \"\'\" + \"\',\'\".join(data) + \"\'\"")
    append_to_file(target_file, "\n".join(txt_content))

@staticmethod
def make_snake_case(clas_name, target_file):
    txt_content = []
    txt_content.append("\n")
    txt_content.append("@staticmethod")
    txt_content.append("def convert_to_snake_case(name):")
    txt_content.append("    import re")
    txt_content.append("    name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', name)")
    txt_content.append("    name = name.lower()")
    txt_content.append("    return name")
    append_to_file(target_file, "\n".join(txt_content))

@staticmethod
def append_to_file(target_file, txt_content):
    try:
        # 读取文件内容
        with open(target_file, 'r', encoding='utf-8') as read_file:
            lines = read_file.readlines()

        # 重写文件内容并追加新内容
        with open(target_file, 'w', encoding='utf-8') as output_file:
            for line in lines:
                output_file.write(line)
            output_file.write(txt_content)

    except FileNotFoundError:
        print(f"Error: The file {target_file} does not exist.")
    except UnicodeDecodeError:
        print(f"Error: Could not decode the file {target_file}. Please check the file encoding.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
